package com.fourth.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourth.dao.EmpInfoDao;
import com.ljx.entity.EmpInfo;
import com.ljx.security.util.WebUtils;
import com.ljx.utils.JwtUtil;
import com.ljx.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.fourth.service.EmpInfoService;
import sun.security.util.Password;

import java.util.Map;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/2/26 15:33
 * @Version 1.0
 */
@Service
public class EmpInfoServiceImpl extends ServiceImpl<EmpInfoDao, EmpInfo> implements EmpInfoService {
	@Autowired(required = false)
	private EmpInfoDao empInfoDao;

	@Autowired
	private PasswordEncoder passwordEncoder;
	@Override
	public Result updatePassword(String newPassword, String oldPassword) {
		// 密码加密器
		BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder()
				;
		// 根据工具类查询出token，token有我们保存的用户信息和权限
		String token = WebUtils.getRequest().getHeader("token");
		Map<String, Object> map = JwtUtil.getTokenChaim(token);
		String username = (String) map.get("username");
		// 根据用户信息查询出用户密码
		QueryWrapper<EmpInfo> wrapper = new QueryWrapper<>();
		wrapper.eq("ename",username);
		EmpInfo empInfo = empInfoDao.selectOne(wrapper);
		String password = empInfo.getPassword();
		// 利用密码加密器将将前端传来的老密码和数据库中的密码作比较，如果true就是密码一致可以修改
		boolean matches = passwordEncoder.matches(oldPassword, password);
		if (matches){
			String newPassword1 = passwordEncoder.encode(newPassword);
			empInfoDao.updatePassword(newPassword1, username);
			return new Result(2000,"密码修改成功",null);
		}
		return new Result(5000,"密码修改失败",null);



	}


}
